package com.bobo.signature.RSA;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
/**
 * Java的RSA数字签名
 * @author win7
 *
 */
public class RSAtest {

	public static String bobo="www.bobo.com";
	public static void main(String[] args) {
		JdkRSA();
	}
	
	
	public static void JdkRSA(){
	    try {
	     //1.初始化秘钥
			KeyPairGenerator keypairGenerator=	KeyPairGenerator.getInstance("RSA");
			keypairGenerator.initialize(512);
			KeyPair keypair= keypairGenerator.generateKeyPair();
			RSAPrivateKey rsaprivateKey= (RSAPrivateKey)keypair.getPrivate();
			RSAPublicKey rsapublicKey=(RSAPublicKey) keypair.getPublic();
			
		//2.执行签名
			PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(rsaprivateKey.getEncoded());
			KeyFactory keyFactory= KeyFactory.getInstance("RSA");
		    PrivateKey privateKey=	keyFactory.generatePrivate(pkcs8EncodedKeySpec);
			Signature signature=Signature.getInstance("MD5withRSA");
			signature.initSign(privateKey);
			signature.update(bobo.getBytes());
			byte[] result= signature.sign();
			System.out.println("Jdk rsa sign:"+HexBin.encode(result));
			
		//3.验证签名
			X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(rsapublicKey.getEncoded());
			KeyFactory factory=KeyFactory.getInstance("RSA");
		    PublicKey publickey= factory.generatePublic(x509EncodedKeySpec);
		    Signature signaturepub=Signature.getInstance("MD5withRSA");
		    signaturepub.initVerify(publickey);
		    signaturepub.update(bobo.getBytes());
		    boolean bool= signaturepub.verify(result);//验证签名是否一致
		    System.out.println(bool);
		} catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | SignatureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
}
